import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_easyloading/src/easy_loading.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/location/mixin/location_page_mixin.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/location/model/today_mileage_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/device_utils.dart';
import 'package:tracker/utils/location_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:tracker/common/push/jpush_utils.dart';

import '../../../../common/constants/app_constants.dart';

import '../../../../provider/notifier/user_info_notifier.dart';
 import '../../../login/model/login_resp.dart';
import '../model/FunctionShowResp.dart';

// 定位页面也叫查看定位
class LocationPage extends ConsumerStatefulWidget {
  const LocationPage({super.key});

  @override
  ConsumerState<LocationPage> createState() => _LocationPageState();
}

class _LocationPageState extends ConsumerState<LocationPage>
    with LocationPageMixin , AutomaticKeepAliveClientMixin, WidgetsBindingObserver{
  @override
  bool get wantKeepAlive => true; // 必须实现
  final GlobalKey bottomViewKey = GlobalKey();
  double bottomViewHeight = 212;

  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  final ScrollController _scrollController = ScrollController();
  String _rememberIMEI = "";

  // 是否定位到设备位置或者手机位置
  bool isLocation = false;
  bool _mapisshow = true;
  BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(39.917215, 116.380341),
      zoomLevel: 17,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  BMFMapController? myMapController;
  BMFMarker? deviceMarker;

  /// 今日里程
  String todayMileage = '0';

  // 多少秒刷新一次
  int refreshTime = 10;
  int countDown = 10;
  final timerUtil = TimerUtil(mTotalTime: 10 * 1000);

  // 点击位置，1:设备位置 2:手机位置 0: 未获取到经纬度时获取显示当前定位的位置
  int clickLocationType = 1;

  bool isLocationExpand = false;  // 地址是否显示全部

  onBMFMapCreated(BMFMapController controller) {
    XLogger.info("onBMFMapCreated");
    myMapController = null;
    deviceMarker = null;
    myMapController = controller;
    myMapController!.showUserLocation(true);
    myMapController?.setMapDidLoadCallback(callback: () async {
      XLogger.debug('地图加载完成');
      final deviceInfo = ref.read(deviceInfoProvider);
      if (deviceInfo.isNineDevice == true) {
        // 定位到手机位置
        isLocation = true;
        await _myLocPlugin.stopLocation();
        _startLocation();
      }
    });
    myMapController?.updateMapOptions(BMFMapOptions(
      logoPosition: BMFLogoPosition.LeftTop,
      showZoomControl: false,
    ));
    _fetchDeviceLocation();
  }


    Future<void> _refreshDeviceInfo() async {
    XLogger.debug('刷新设备信息 --- ');
    final deviceInfo = ref.watch(deviceInfoProvider);
    int? oldDeviceMode = deviceInfo.deviceMode;

    var res = await get<HomeDeviceInfoResp, HomeDeviceInfoResp>(
        '/home/deviceInfo',
        queryParameters: {'imei':""},
        decodeType: HomeDeviceInfoResp());
    res.when(
        success: (HomeDeviceInfoResp resp) async {
          XLogger.info(res.toString());
          if (resp.code == 200) {

            if (resp.data == null || resp.data!.deviceInfo == null) {
              ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
              setState(() {});
              return;
            }

            var deviceInfoVO = resp.data!.deviceInfo!;
            deviceInfoVO.deviceMode = oldDeviceMode;
            ref.read(deviceInfoProvider.notifier).setDeviceInfo(deviceInfoVO);
            setState(() {});
          } else if (resp.code == 60001) {
            // 无设备信息，移除显示设备
            ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
            setState(() {});
          } else {
            // setState(() {
            //   hasThing = false;
            // });
            XLogger.debug(resp.msg);
          }
        },
        failure: (String msg, int code) {});
  }

  /// 获取设备实时信息
  Future<void> _fetchDeviceLocation() async {
    // XLogger.info('获取设备实时信息');
    // XLogger.info(timerUtil.isActive());

    // 10秒的时候不允许点击刷新
    if (timerUtil.isActive() && countDown >= 9) {
      return;
    }
    final deviceInfo = ref.watch(deviceInfoProvider);
    XLogger.info(deviceInfo.toJson());
    XLogger.info(deviceInfo.imei);
    XLogger.info(_rememberIMEI);
    XLogger.info(deviceInfo.deviceMode);

    if (_rememberIMEI != deviceInfo.imei &&
        (deviceInfo.imei ?? "").isNotEmpty) {
      XLogger.info("设置别名");
      _rememberIMEI = deviceInfo.imei ?? "";
      JPushUtils.setAlias(deviceInfo.imei ?? "");
    }

    if (deviceInfo.isNineDevice == true) {
      MonitorData fakeMonitorData = MonitorData();
      fakeMonitorData.deviceName = deviceInfo.deviceName;
      fakeMonitorData.batteryPercentage = 100;
      fakeMonitorData.csq = 30;
      fakeMonitorData.deviceStatus = 2; // 离线
      fakeMonitorData.motionStateText = '静止';
      fakeMonitorData.workModeName = '智能模式';
      fakeMonitorData.locationType = 1;
      fakeMonitorData.altitude = 0;
      fakeMonitorData.lastCommunicationTime = DateUtil.formatDate(
          DateTime.now().subtract(const Duration(seconds: 10)),
          format: 'yyyy-MM-dd HH:mm:ss');
       setState(() {
        monitorData = fakeMonitorData;
      });
      ref.read(monitorDataProvider.notifier).state =
          fakeMonitorData ;
      // 解析地址
      getNineDeviceAddress();
      // 开启倒计时
      countDown = refreshTime;
      timerUtil.updateTotalTime(refreshTime * 1000);
      return;
    } else {
      // 开启倒计时
      countDown = refreshTime;
      timerUtil.updateTotalTime(refreshTime * 1000);
    }

    _fetchDeviceTodayMileage(deviceInfo.imei!).then((value) {
      if (mounted) {
        setState(() {
          var mm = value / 1000;
          // 格式化，最多保留两位小数，小数点后为0就不显示
          todayMileage = NumUtils.formatNum(mm);
        });
      }
    });

    getDeviceMode();
    XLogger.info("获取设备信息");
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei},
        decodeType: MonitorDataResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        // 测试经纬度为空
        if (mounted) {
          setState(() {
            monitorData = resp.data;
            ref.read(monitorDataProvider.notifier).state =
                monitorData ?? MonitorData();
          });
        }
        if (resp.data?.latitude != null) {
          hasLocation = true;
          setState(() {});
          _drawDeviceMarker(resp.data!.latitude!, resp.data!.longitude!);
        } else {
          hasLocation = false;
          // 返回的实时信息中没有经纬度，默认为基站定位
          monitorData?.locationType = 3;
          // 经纬度为空，定位到手机位置，解析当前经纬度
          XLogger.info('phoneAddress: $phoneAddress');
          if (phoneAddress != null) {
            monitorData?.longitude = phoneLocation?.longitude;
            monitorData?.latitude = phoneLocation?.latitude;
            monitorData?.address = phoneAddress;

            setState(() {});

            _drawDeviceMarker(monitorData!.latitude!, monitorData!.longitude!);
          } else {
            clickLocationType = 0;
            _startLocation();
          }
        }

        // 开启倒计时
        countDown = refreshTime;
        timerUtil.updateTotalTime(refreshTime * 1000);
      } else {
        if (resp.msg != null) {
          ToastUtils.showToast(resp.msg!);
        }
      }
      return null;
    }, failure: (String msg, int code) {
      XLogger.error('获取设备实时信息失败：msg: $msg, code: $code');
    });
  }

  _loadSaveShowAnfang() async {

  }

  _drawDeviceMarker(double latitude, double longitude) {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return;
    }
    if (_mapisshow == false) {
      return;
    }
    myMapController?.setCenterCoordinate(
        BMFCoordinate(latitude, longitude), true);
    if (deviceMarker == null) {
      final double scale = _getMarkerIconScale();
      deviceMarker = BMFMarker.icon(
        position: BMFCoordinate(latitude, longitude),
        icon: getDeviceIcon(monitorData?.deviceStatus),
        identifier: 'deviceMarker',
        scaleX: scale,
        scaleY: scale,
      );
      myMapController?.addMarker(deviceMarker!);
    } else {
      deviceMarker?.updatePosition(BMFCoordinate(latitude, longitude));
      deviceMarker?.updateIcon(getDeviceIcon(monitorData?.deviceStatus));
    }
    XLogger.error(deviceMarker);
    XLogger.error(myMapController);

    XLogger.error("绘制车头");

  }

  /// 获取设备今日里程
  Future<num> _fetchDeviceTodayMileage(String imei) async {
    final res = await post<TodayMileageResp, TodayMileageResp>(
        '/device/getTodayMileage',
        data: {'imei': imei},
        decodeType: TodayMileageResp());
    return res.when(success: (resp) {
      if (resp.code == 200) {
        return resp.data ?? 0;
      }
      return 0;
    }, failure: (String msg, int code) {
      XLogger.error('获取设备今日里程：msg: $msg, code: $code');
      return 0;
    });
  }

  /// 获取marker图标缩放比例
  double _getMarkerIconScale() {
    // final density = ScreenUtil.getScreenDensity(context);
    // XLogger.info('density: $density');
    // final double scale = 1 + (density) / 10;
    // XLogger.info('scale: $scale');
    return 0.8;
  }
  Future<void> showFunctionConfig() async {

    final deviceInfo = ref.read(deviceInfoProvider);
    final userType = ref.read(userTypeProvider);
    XLogger.info(userType.value);
    String? imei;
   // type4 是设备号登录
     if (deviceInfo.imei == null && userType.value == '4') {
       LoginData loginData = SpUtil.getObj('loginData', (v) => LoginData().fromJson(v), defValue: LoginData());
      imei = loginData.imei;
    }else {
      imei = deviceInfo.imei;
    }
     deviceInfo.imei = imei;

    final buttonShow = ref.read(buttonShowProvider);

    final res = await get<FunctionShowResp, FunctionShowResp>(
        '$newBaseULr/device/function/list?imei=$imei',
        decodeType: FunctionShowResp());
    res.when(success: (resp) async {

      if (resp.data is List) {
        final list = resp.data as List<FunctionDetails>;

        int anfangluyinValue = 0;
        int zengzhifuwuValue = 0;
        int shengyinbaojingValue = 0;
        // 方式1：for-in 循环
        for (var item in list) {
          if (item.functionName == '安防录音') {
            anfangluyinValue = item.functionStatus ?? 0;
          }else if (item.functionName == '增值服务') {
            zengzhifuwuValue = item.functionStatus ?? 0;
          }else {
            shengyinbaojingValue = item.functionStatus ?? 0;
          }
        }
        ref.read(buttonShowProvider.notifier).state = buttonShow.copyWith(
            showanfangluyin: anfangluyinValue,
            showzengzhifuwu: zengzhifuwuValue,
            showshengyinbaojing: shengyinbaojingValue,
        );
      }
    }, failure: (String msg, int code) {
      XLogger.info(msg);

    });
  }
  /// 构建新设备信息卡片
  Widget _buildNewInfoCard() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final userType = ref.watch(userTypeProvider);
    final userInfo = ref.watch(userInfoProvider);
    // XLogger.info(deviceInfo.toJson());
    // XLogger.info(userInfo.toJson());

    var username = getLoginName(userType, userInfo, deviceInfo);
    // XLogger.info(userType);

    // XLogger.info(username);
    const fontSize = 14.0;
    return Container(
      // alignment: Alignment.centerLeft,

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 信号
          Container(
              height: 35,
              decoration: BoxDecoration(
                color: AppTheme.themeConfig.navBarColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(6),
                  topRight: Radius.circular(6),
                ),
              ),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Row(
                  children: [
                    _buildBatteryInfo(fontSize),
                    _buildCsqInfo(fontSize),
                  ],
                ),
              )),
          const SizedBox(height: 4),
          // 用户信息
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 6),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  width: 35,
                  padding: const EdgeInsets.all(10),
                  decoration: const BoxDecoration(shape: BoxShape.circle),
                  child: Image(
                    image: AssetImage(getDeviceIcon(monitorData?.deviceStatus)),
                  ),
                ),
                // lpText(username, size: 12),
                lpText(deviceInfo.imei ?? "", size: 12),
                Expanded(
                    child: Align(
                  alignment: Alignment.centerLeft,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                      color: Color(0xFFEEEEEF),
                    ),
                    child:
                    //(deviceInfo.deviceMode == 2 && monitorData?.deviceStatus == 4) ? Container() :
                    Text(
                      // 关闭模式不显示
                      (monitorData?.deviceStatus == 1 || monitorData?.deviceStatus == 4)
                          ? '${DeviceUtils.getStatusText(monitorData?.deviceStatus)}'
                          : '${DeviceUtils.getStatusText(monitorData?.deviceStatus)} ${_getStaticTime()}',
                      style: TextStyle(
                          fontSize: 13,
                          color: AppTheme.themeConfig.primaryColor,
                          backgroundColor: Color(0xFFEEEEEF)),
                    ),
                  ),
                )),
                // 故障自检按钮
                TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: Size(45, 30),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 5, vertical: 0),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(2),
                      ),
                      backgroundColor: Color(0xFFEEEEEF),
                    ),
                    onPressed: () {
                      _handleSelfTest(deviceInfo);
                    },
                    child: Text("故障自检",
                        style: TextStyle(color: Color(0xFFE50012)))),
              ],
            ),
          ),

          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                TextButton(
                  style: TextButton.styleFrom(
                    minimumSize: Size(45, 30),
                    padding:
                        const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(6),
                    ),
                    backgroundColor: AppTheme.themeConfig.primaryColor,
                  ),
                  onPressed: () {
                     context.push(RouterManager.changeIcon).then((value) async {
                      if (value == true) {
                        await loadSavedString();
                        await deviceMarker?.updateIcon(
                            getDeviceIcon(monitorData?.deviceStatus));
                        ref.read(updateIconProvider.notifier).state += 1;
                      }
                      setState(() {
                        isLocationExpand = false;
                       });
                    });
                  },
                  child: Text(
                    "更换",
                    style: TextStyle(
                      fontSize: fontSize,
                      color: Colors.white,
                    ),
                  ),
                ),
                isExpandLocation(),
              ],
            ),
          ),
          //
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
            child: Text(
                '今日里程：${todayMileage}km  |  速度：${monitorData?.speed ?? '0'}km/h',
                style: TextStyle(
                    fontSize: fontSize,
                    color: AppTheme.themeConfig.primaryTextColor)),
          ),
          const SizedBox(height: 4),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
            child: Text(
                (deviceInfo.deviceMode == null) ? '定位模式：${monitorData?.workModeName ?? "    "}  |  ${_buildNewLocationModeInfo()}' :
                (deviceInfo.deviceMode == 0)
                    ? '定位模式：智能模式  |  ${_buildNewLocationModeInfo()}'
                    : deviceInfo.deviceMode == 1
                        ? '定位模式：省电模式  |  ${_buildNewLocationModeInfo()}'
                        : deviceInfo.deviceMode == 3 ? '定位模式：秒定模式  |  ${_buildNewLocationModeInfo()}' : '定位模式：关闭定位  |  ${_buildNewLocationModeInfo()}' ,
                style: TextStyle(
                    fontSize: fontSize,
                    color: AppTheme.themeConfig.primaryTextColor)),
          ),
          const SizedBox(height: 4),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
            child: Text('通讯时间：${monitorData?.lastCommunicationTime ?? ''}',
                style: TextStyle(
                    fontSize: fontSize,
                    color: AppTheme.themeConfig.primaryTextColor)),
          ),
        ],
      ),
    );
  }

  Widget isExpandLocation() {
    if (isLocationExpand == true) {
      return Padding(
        padding: EdgeInsets.only(left: 5),
        child: Container(
          // color: Colors.blue,
          width: ScreenUtil.getScreenW(context) - 85,
          child: Text(
            monitorData?.address ?? '',
            textAlign: TextAlign.left,
            maxLines: 2,
            style: TextStyle(
                fontSize: 14,
                // color: AppTheme.themeConfig.infoTextColor,
                fontWeight: FontWeight.normal),
            // overflow: TextOverflow.ellipsis,
          ),
        ),
      );
    } else {
      return TextButton(
        style: ButtonStyle(
          minimumSize: MaterialStateProperty.all(Size.zero),
          tapTargetSize: MaterialTapTargetSize.shrinkWrap,

          foregroundColor: MaterialStateProperty.all<Color>(
              AppTheme.themeConfig.primaryColor), // 设置文本颜色为蓝色，类似超链接颜色
          textStyle: MaterialStateProperty.all<TextStyle>(
            TextStyle(
              decoration: TextDecoration.underline, // 添加下划线装饰
              fontSize: 14,
            ),
          ),
        ),
        onPressed: () {
          if (isLocationExpand == true) {
          } else {
            setState(() {
              isLocationExpand = true;
            });
            // _chakandizhi();
          }
        },
        child: Text('显示位置'),
      );
    }
  }

  /// 构建设备信息卡片
  Widget _buildInfoCard() {
    const fontSize = 13.0;
    return Container(
      alignment: Alignment.centerLeft,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildDeviceStatusView(fontSize),
              Row(
                children: [
                  _buildBatteryInfo(fontSize),
                  _buildCsqInfo(fontSize),
                ],
              )
            ],
          ),
          const SizedBox(height: 4),
          Text('设备名称: ${monitorData?.deviceName ?? ''}',
              style: TextStyle(
                  fontSize: fontSize,
                  color: AppTheme.themeConfig.primaryTextColor)),
          Text('静止时长: ${_getStaticTime()}',
              style: TextStyle(
                  fontSize: fontSize,
                  color: AppTheme.themeConfig.primaryTextColor)),
          Row(
            children: [
              Text('今日里程: ${todayMileage}km',
                  style: TextStyle(
                      fontSize: fontSize,
                      color: AppTheme.themeConfig.primaryTextColor)),
              const SizedBox(width: 12),
              Text('定位模式: ${monitorData?.workModeName ?? ''}',
                  style: TextStyle(
                      fontSize: fontSize,
                      color: AppTheme.themeConfig.primaryTextColor)),
            ],
          ),
          _buildLocationModeInfo(),
          Text('通讯时间: ${monitorData?.lastCommunicationTime ?? ''}',
              style: TextStyle(
                  fontSize: fontSize,
                  color: AppTheme.themeConfig.primaryTextColor)),
          _buildAddressInfo(),
        ],
      ),
    );
  }

  /// 电量
  _buildBatteryInfo(double fontSize) {
    // XLogger.info(monitorData);

    if (monitorData?.batteryPercentage == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          _getBatteryImage(monitorData?.batteryPercentage),
          width: 28,
          height: 20,
          fit: BoxFit.fitWidth,
        ),
        const SizedBox(width: 4),
        Text('${monitorData?.batteryPercentage ?? ''}%',
            style: TextStyle(
                fontSize: fontSize,
                color: AppTheme.themeConfig.primaryTextColor)),
        const SizedBox(width: 12),
      ],
    );
  }

  /// 信号
  _buildCsqInfo(double fontSize) {
    if (monitorData?.csq == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          // _getCsqLevelImage(monitorData?.csq),
          "assets/images/location/liuliang.png",
          width: 24,
          height: 16,
          fit: BoxFit.contain,
        ),
        const SizedBox(width: 4),
        Text('${monitorData?.csq ?? ''}',
            style: TextStyle(
                fontSize: fontSize,
                color: AppTheme.themeConfig.primaryTextColor)),
      ],
    );
  }

  /// 设备状态文本
  Widget _buildDeviceStatusView(double fontSize) {
    var list = <Widget>[];
    list.add(Text(
        '设备状态: ${DeviceUtils.getStatusText(monitorData?.deviceStatus)}',
        style: TextStyle(
            fontSize: fontSize, color: AppTheme.themeConfig.primaryTextColor)));
    // 设备状态是[离线]或者[远程关机]，就不要显示[运动]or[静止]了
    if (monitorData?.deviceStatus == 1 || monitorData?.deviceStatus == 3) {
      // 设备状态是在线或者深度休眠，就显示运动or静止
      if (monitorData?.motionStateText != null) {
        list.add(Text(', ${monitorData?.motionStateText}',
            style: TextStyle(
                fontSize: fontSize,
                color: AppTheme.themeConfig.primaryTextColor)));
      }
    }
    return Row(
      children: list,
    );
  }

  /// 根据定位模式不同，显示不同的信息
  Widget _buildLocationModeInfo() {
    // 定位模式: 1:GPS定位 2:WIFI定位 3:基站定位
    if (monitorData?.locationType == 1) {
      // GPS定位
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                  '定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}',
                  style: TextStyle(
                      fontSize: 13,
                      color: AppTheme.themeConfig.primaryTextColor)),
              const SizedBox(width: 12),
              // 速度
              Text('速度: ${monitorData?.speed ?? '0'}km/h',
                  style: TextStyle(
                      fontSize: 13,
                      color: AppTheme.themeConfig.primaryTextColor)),
              // 海拔，如果海拔为0就不显示
              _buildAltitudeInfo(),
            ],
          ),
        ],
      );
    } else {
      // 2:WIFI定位 3:基站定位
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
              '定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}',
              style: TextStyle(
                  fontSize: 13, color: AppTheme.themeConfig.primaryTextColor)),
        ],
      );
    }
  }

  /// 根据定位模式不同，显示不同的信息
  String _buildNewLocationModeInfo() {
    // 定位模式: 1:GPS定位 2:WIFI定位 3:基站定位
    if (monitorData?.locationType == 1) {
      return '定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}';
    } else {
      // 2:WIFI定位 3:基站定位
      return '定位类型: ${LocationUtils.getLocationTypeText(monitorData?.locationType)}';
    }
  }

  /// 海拔信息
  Widget _buildAltitudeInfo() {
    if (monitorData?.altitude == 0) {
      return Container();
    }
    return Row(
      children: [
        const SizedBox(width: 12),
        Text('海拔: ${monitorData?.altitude ?? '0'}m',
            style: TextStyle(
                fontSize: 13, color: AppTheme.themeConfig.primaryTextColor))
      ],
    );
  }

  /// 构建地址信息
  Widget _buildAddressInfo() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    String address = '';
    if (deviceInfo.isNineDevice == true) {
      address = nineDeviceAddress ?? '';
    } else {
      address = monitorData?.address ?? '';
    }
    return Column(
      children: [
        const SizedBox(height: 4),
        Divider(
          height: 1,
          color: ColorUtils.hexToColor('#E5E5E5'),
        ),
        const SizedBox(height: 4),
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            '地址: ${address}',
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 13,
              color: AppTheme.themeConfig.primaryTextColor,
            ),
          ),
        ),
      ],
    );
  }

  _chakandizhi() {
    showDialog(
        context: context,
        builder: (_context) {
          return AlertDialog(
            title: const Text('查看地址'),
            content: Container(
              child: Column(
                // 最小高度
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('地址：${monitorData?.address ?? '0'}'),
                ],
              ),
            ),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(_context).pop();
                },
                child: const Text('好的'),
              ),
            ],
          );
        });
  }

  /// 点击自检
  _handleSelfTest(DeviceInfoVO deviceInfo) async {
    // 加载进度，延迟2s
    ToastUtils.showLoading(status: '正在自检', maskType: EasyLoadingMaskType.black);
    Future.delayed(const Duration(seconds: 2), () {
      if (deviceInfo.isNineDevice == true) {
        ToastUtils.dismissLoading();
        MonitorData monitorData = MonitorData();
        monitorData.batteryPercentage = 100;
        monitorData.deviceStatus = 1;
        monitorData.chargingStatusName = '未充电';
        monitorData.workModeName = '智能模式';
        monitorData.csq = 30;
        monitorData.locationPriority = '优先GPS';
        monitorData.iccid = deviceInfo.imei;
        monitorData.address = '';
        // 时间等于现在的时间减去10秒
        monitorData.lastCommunicationTime = DateUtil.formatDate(
            DateTime.now().subtract(const Duration(seconds: 10)),
            format: 'yyyy-MM-dd HH:mm:ss');
        ;
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
        ref.read(monitorDataProvider.notifier).state =
            monitorData ;
        return;
      }
      _handleSelfTestData();
    });
  }

  _handleSelfTestData() async {
    XLogger.info("获取设备信息");
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei},
        decodeType: MonitorDataResp());
    res.when(success: (MonitorDataResp resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果地址为空，则请求接口获取地址
        if (resp.data == null) {
          return;
        }
        var monitorData = resp.data!;

        // 没有经纬度，不请求逆地理编码
        final prefs = await SharedPreferences.getInstance();
        await prefs.setInt(
            'batteryPercentage', monitorData.batteryPercentage ?? 100);
        if ((monitorData.address == null || monitorData.address!.isEmpty) &&
            monitorData.latitude != null &&
            monitorData.longitude != null) {
          monitorData.address = await DeviceUtils.reverseGeoCode(
              latitude: monitorData.latitude!,
              longitude: monitorData.longitude!);
        }
        ref.read(monitorDataProvider.notifier).state =
            monitorData;
        await prefs.setString('monitorDataAddress', monitorData.address ?? "");
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
    });
  }

  /// 计算静止时长
  /// 显示现在的时间与定位时间的时间差，并且注意，时间差小于5分钟就显示0天0小时0分钟
  String _getStaticTime() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return '0分';
    }
    // 没有经纬度，显示0分钟
    if (!hasLocation) {
      return '0分';
    }
    if (monitorData?.gpsTime == null) {
      return '';
    }
    final gpsTime = DateTime.parse(monitorData!.gpsTime!);
    final now = DateTime.now();
    final difference = now.difference(gpsTime);
    if (difference.inMinutes < 5) {
      return '0天0小时0分';
    }
    final days = difference.inDays;
    final hours = difference.inHours - days * 24;
    final minutes = difference.inMinutes - days * 24 * 60 - hours * 60;
    // days、hours大于1才显示
    if (days > 0) {
      return '${days}天${hours}小时${minutes}分';
    } else if (hours > 0) {
      return '${hours}小时${minutes}分';
    } else {
      return '${minutes}分';
    }
  }

  /// 根据电量值获取电量图标
  String _getBatteryImage(int? battery) {
    if (monitorData?.chargingStatus == 0) {
      return 'assets/images/home/charging.png';
    }
    int batteryLevel = 0;
    if (battery == null) {
      return 'assets/images/home/power20.png';
    }

    if (monitorData?.deviceStatus == 2 && battery < 20) {
      // 离线
      battery = 0;
    }

    if (battery <= 20) {
      return 'assets/images/home/power20.png';
    } else if (battery <= 40) {
      return 'assets/images/home/power40.png';
    } else if (battery <= 60) {
      return 'assets/images/home/power60.png';
    } else if (battery <= 80) {
      return 'assets/images/home/power80.png';
    } else if (battery <= 100) {
      return 'assets/images/home/power100.png';
    }
    return 'assets/images/home/power100.png';
  }

  /// 根据信号值获取信号图标
  String _getCsqLevelImage(int? csq) {
    int csqLevel = 0;
    if (csq != null) {
      if (csq <= 5) {
        csqLevel = 0;
      } else if (csq <= 8) {
        csqLevel = 1;
      } else if (csq <= 12) {
        csqLevel = 2;
      } else if (csq <= 16) {
        csqLevel = 3;
      } else if (csq <= 23) {
        csqLevel = 4;
      } else {
        csqLevel = 5;
      }
    }
    return 'assets/images/device/csq_$csqLevel.png';
  }

  /// 根据页面地址打开页面
  openPageByPath(String path, String menuCode) async {
    if (path.startsWith('http')) {
      await context
          .push('${RouterManager.web}?url=${Uri.encodeComponent(path)}');
    } else {
      _mapisshow = false;
      await context.push(path).then((value){
        setState(() {
          _mapisshow = true;
        });
      });
    }
    setState(() {
      isLocationExpand = false;
    });
  }

  /// 构建右上角按钮
  Widget _buildTopRightView() {
    final deviceInfo = ref.watch(deviceInfoProvider);

    return Positioned(
      right: 10,
      top: Platform.isIOS ? 100 : 80,
      child: Column(
        children: [

          SizedBox(
            height: 20,
          ),
          // 电子围栏按钮
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(
                color: AppTheme.themeConfig.disableTextColor,
                width: 1.0,
              ),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(
              children: [
                GestureDetector(
                  onTap: () {
                    // 切换标准地图和卫星图
                    myMapController?.getMapType().then((value) {
                      if (value == BMFMapType.Standard) {
                        myMapController?.updateMapOptions(
                            BMFMapOptions(mapType: BMFMapType.Satellite));
                      } else {
                        myMapController?.updateMapOptions(
                            BMFMapOptions(mapType: BMFMapType.Standard));
                      }
                    });
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      // border: Border.all(
                      //   color: AppTheme.themeConfig.disableTextColor,
                      //   width: 1.0,
                      // ),
                      // borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // Image(image:
                        //   AssetImage("assetName")
                        // )
                        Icon(
                          Icons.layers_outlined,
                          color: AppTheme.themeConfig.primaryTextColor,
                        ),
                        Text(
                          '卫星地图',
                          style: TextStyle(
                            fontSize: 8,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                  color: AppTheme.themeConfig.disableTextColor,
                  width: 1.0,
                ),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(children: [
                GestureDetector(
                  onTap: () {
                    // 电子围栏
                    String path = '/fence';
                    path = '${path}?imei=${deviceInfo.imei}';
                    openPageByPath(path, 'fence');
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image(
                            width: 20,
                            height: 20,
                            image: AssetImage(
                                "assets/images/home/dianziweilan.png")),
                        Text(
                          '电子围栏',
                          style: TextStyle(
                            fontSize: 8,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                // 追踪导航按钮
                GestureDetector(
                  onTap: () {
                    // 导航
                    _navigation();
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image(
                            width: 20,
                            height: 20,
                            image: AssetImage(
                                "assets/images/home/zhuizongdaohang.png")),
                        Text(
                          '追踪导航',
                          style: TextStyle(
                            fontSize: 8,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ])),
          SizedBox(
            height: 10,
          ),
          Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                  color: AppTheme.themeConfig.disableTextColor,
                  width: 1.0,
                ),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(children: [
                GestureDetector(
                  onTap: () {
                    // 切换标准地图和卫星图
                    myMapController?.zoomIn();
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '+',
                          style: TextStyle(
                            fontSize: 28,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                // 追踪导航按钮
                GestureDetector(
                  onTap: () {
                    // 切换标准地图和卫星图
                    myMapController?.zoomOut();
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '—',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 24,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ])),
          SizedBox(
            height: 10,
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(
                color: AppTheme.themeConfig.disableTextColor,
                width: 1.0,
              ),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(
              children: [
                GestureDetector(
                  onTap: () async {
                    if (deviceInfo.isNineDevice == true) {
                      return;
                    }
                    // 移动到设备位置
                    myMapController?.setCenterCoordinate(
                        BMFCoordinate(monitorData?.latitude ?? 0,
                            monitorData?.longitude ?? 0),
                        true);
                  },
                  child: Container(
                      alignment: Alignment.center,
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image(
                            image:
                                AssetImage('assets/images/location/ceju.png'),
                            width: 24,
                            height: 24,
                            fit: BoxFit.contain,
                          ),
                          Text(
                            '设备位置',
                            style: TextStyle(
                              fontSize: 8,
                              color: AppTheme.themeConfig.secondaryTextColor,
                            ),
                          )
                        ],
                      )),
                ),
                const SizedBox(height: 12),
                // 手机位置
                GestureDetector(
                  onTap: () async {
                    if (deviceInfo.isNineDevice == true) {
                      return;
                    }
                    // 定位到手机位置
                    clickLocationType = 2;
                    isLocation = true;
                    await _myLocPlugin.stopLocation();
                    _startLocation();
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/location/weizhi.png',
                          width: 24,
                          height: 24,
                          fit: BoxFit.contain,
                        ),
                        Text(
                          '我的位置',
                          style: TextStyle(
                            fontSize: 8,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 切换设备
  Widget _changeDevicd() {
    return TextButton(
      onPressed: () {
        final userType = ref.watch(userTypeProvider);
        if (userType == UserTypeEnum.device) {
          ToastUtils.showDeviceLoginDialog(context);
        } else {
          _mapisshow = false;
          context.push(RouterManager.deviceList).then((value) {
            setState(() {
              isLocationExpand = false;
              _mapisshow = true;
            });
          });

        }
      },
      style: TextButton.styleFrom(
        minimumSize: Size(40, 40),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(6),
          side: BorderSide(
            color: AppTheme.themeConfig.disableTextColor,
            width: 1,
          ),
        ),
        backgroundColor: ColorUtils.hexToColor('#FFFFFF'),
      ),
      child: Text(
        '切换设备',
        style: TextStyle(
          fontSize: 17,
          color: AppTheme.themeConfig.primaryTextColor,
        ),
      ),
    );
  }

  Widget _topView() {
    return Positioned(
      top: 0,
      child: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: EdgeInsets.only(
              left: 10, right: 10, top: MediaQuery.of(context).padding.top),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {
                  // 刷新设备位置
                  _fetchDeviceLocation();
                },
                style: TextButton.styleFrom(
                  minimumSize: Size(40, 40),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                    side: BorderSide(
                      color: AppTheme.themeConfig.disableTextColor,
                      width: 1,
                    ),
                  ),
                  backgroundColor: ColorUtils.hexToColor('#FFFFFF'),
                ),
                child: Text(
                  '${countDown}s',
                  style: TextStyle(
                    // overflow: TextOverflow.ellipsis, // 设置文本溢出时显示省略号

                    fontSize: 14,
                    color: AppTheme.themeConfig.primaryTextColor,
                  ),
                ),
              ),
              Expanded(
                  child: alarmData != null
                      ? Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 5),
                          child: TextButton(
                            onPressed: () {
                               context.push(RouterManager.msg).then((value) {
                                setState(() {
                                  isLocationExpand = false;
                                 });
                              });

                            },
                            style: TextButton.styleFrom(
                              minimumSize: Size(40, 40),
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 5),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(6),
                                side: BorderSide(
                                  color: AppTheme.themeConfig.disableTextColor,
                                  width: 1,
                                ),
                              ),
                              backgroundColor: ColorUtils.hexToColor('#FFFFFF'),
                            ),
                            child: lpText(
                                "您的设备${DateUtil.formatDate(alarmData?.occurTime, format: 'yyyy/MM/dd HH:mm:ss')}${alarmData?.warnDesc}",
                                size: 16,
                                maxLine: 1,
                                textOverflow: TextOverflow.ellipsis),
                          ),
                        )
                      : const Center()),
              _changeDevicd()
            ],
          ),
        ),
      ),
    );
  }

  /// 构建左下角按钮
  Widget _buildBottomleftView() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 设置高度
    return Positioned(
        right: 10,
        bottom: bottomViewHeight + 60,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6),
            border: Border.all(
              color: AppTheme.themeConfig.disableTextColor,
              width: 1.0,
            ),
          ),
          child: Column(
            children: [
              // 设备位置
              GestureDetector(
                onTap: () async {
                  if (deviceInfo.isNineDevice == true) {
                    return;
                  }
                  // 移动到设备位置
                  myMapController?.setCenterCoordinate(
                      BMFCoordinate(monitorData?.latitude ?? 0,
                          monitorData?.longitude ?? 0),
                      true);
                },
                child: Container(
                    alignment: Alignment.center,
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image(
                          image: AssetImage('assets/images/location/ceju.png'),
                          width: 24,
                          height: 24,
                          fit: BoxFit.contain,
                        ),
                        Text(
                          '设备位置',
                          style: TextStyle(
                            fontSize: 8,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        )
                      ],
                    )),
              ),
              const SizedBox(height: 12),
              // 手机位置
              GestureDetector(
                onTap: () async {
                  if (deviceInfo.isNineDevice == true) {
                    return;
                  }
                  // 定位到手机位置
                  clickLocationType = 2;
                  isLocation = true;
                  await _myLocPlugin.stopLocation();
                  _startLocation();
                },
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/images/location/weizhi.png',
                        width: 24,
                        height: 24,
                        fit: BoxFit.contain,
                      ),
                      Text(
                        '位置',
                        style: TextStyle(
                          fontSize: 8,
                          color: AppTheme.themeConfig.secondaryTextColor,
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ));
  }

   _buildBottomView() {
     final showButton = ref.watch(buttonShowProvider);
    return Positioned(
        left: 0,
        right: 0,
        bottom: 0,
        child: Container(
          key: bottomViewKey,
          width: double.infinity,
          // height: 120,
          padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 2),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              // _buildInfoCard(),
              _buildNewInfoCard(),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: TextButton(
                        onPressed: () {
                           context.push(RouterManager.deviceInfo).then((value){
                            setState(() {
                              isLocationExpand = false;
                             });
                          });

                        },
                        style: TextButton.styleFrom(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          backgroundColor: AppTheme.themeConfig.primaryColor,
                        ),
                        child: const Text(
                          '设备信息',
                          style: TextStyle(
                            fontSize: 15,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    if (showButton.showanfangluyin == 1)
                    Expanded(
                      flex: 1,
                      child: TextButton(
                        onPressed: () {
                          context.push(RouterManager.recordHistory).then((value){
                             setState(() {
                              isLocationExpand = false;
                             });
                          });

                        },
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 8),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          backgroundColor: AppTheme.themeConfig.primaryColor,
                        ),
                        child: const Text(
                          '安防录音',
                          style: TextStyle(
                            fontSize: 15,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      flex: 1,
                      child: TextButton(
                          onPressed: () {
                            context.push(RouterManager.track).then((value){
                            setState(() {
                              isLocationExpand = false;
                             });
                          });
                        },
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 8),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          backgroundColor: AppTheme.themeConfig.primaryColor,
                        ),
                        child: const Text(
                          '轨迹回放',
                          style: TextStyle(
                            fontSize: 15,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  /// 导航
  void _navigation() async {
    final availableMaps = await MapLauncher.installedMaps;
    XLogger.info(availableMaps);
    if (availableMaps.isNotEmpty) {
      // 显示bottomSheet
      _showMapSheet(availableMaps);
    } else {
      ToastUtils.showToast('没有安装地图软件');
    }
  }

  /// 显示地图选择
  _showMapSheet(List<AvailableMap> availableMaps) {
    final mapTitleMap = {
      'amap': '高德地图',
      'baidu': '百度地图',
      'google': '谷歌地图',
      'apple': '苹果地图',
      'google': '谷歌地图',
      'tencent': '腾讯地图',
    };
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: availableMaps.length * 60,
          child: ListView.builder(
            itemCount: availableMaps.length,
            itemBuilder: (BuildContext context, int index) {
              final map = availableMaps[index];
              final mapName =
                  mapTitleMap[map.mapType.name.toLowerCase()] ?? map.mapName;
              return ListTile(
                onTap: () {
                  map.showDirections(
                      destination: Coords(monitorData?.latitude ?? 0,
                          monitorData?.longitude ?? 0),
                      destinationTitle: monitorData?.address ?? '');
                  // map.showMarker(
                  //   coords: Coords(monitorData?.latitude ?? 0, monitorData?.longitude ?? 0),
                  //   title: monitorData?.address ?? '',
                  // );
                  Navigator.pop(context);
                },
                title: Text(mapName),
              );
            },
          ),
        );
      },
    );
  }

  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        // 定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        locationMode: BMFLocationMode.hightAccuracy,
        // 是否需要返回地址信息
        isNeedAddress: true,
        // 是否需要返回海拔高度信息
        isNeedAltitude: true,
        // 是否需要返回周边poi信息
        isNeedLocationPoiList: true,
        // 是否需要返回新版本rgc信息
        isNeedNewVersionRgc: true,
        // 是否需要返回位置描述信息
        isNeedLocationDescribe: true,
        // 是否使用gps
        openGps: true,
        // 可选，设置场景定位参数，包括签到场景、运动场景、出行场景
        locationPurpose: BMFLocationPurpose.sport,
        // 坐标系
        coordType: BMFLocationCoordType.gcj02,
        // 设置发起定位请求的间隔，int类型，单位ms
        // 如果设置为0，则代表单次定位，即仅定位一次，默认为0
        scanspan: 5000);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
      // 坐标系
      coordType: BMFLocationCoordType.gcj02,
      // 位置获取超时时间
      locationTimeout: 10,
      // 获取地址信息超时时间
      reGeocodeTimeout: 10,
      // 应用位置类型 默认为automotiveNavigation
      activityType: BMFActivityType.automotiveNavigation,
      // 设置预期精度参数 默认为best
      desiredAccuracy: BMFDesiredAccuracy.best,
      // 是否需要最新版本rgc数据
      isNeedNewVersionRgc: true,
      // 指定定位是否会被系统自动暂停
      pausesLocationUpdatesAutomatically: false,
      // 指定是否允许后台定位,
      // 允许的话是可以进行后台定位的，但需要项目
      // 配置允许后台定位，否则会报错，具体参考开发文档
      allowsBackgroundLocationUpdates: true,
      // 设定定位的最小更新距离
      distanceFilter: 10,
    );
    return options;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      setState(() {
        _mapisshow = true;
      });
      XLogger.info("进前台");
    }else if (state == AppLifecycleState.paused){
      XLogger.info("退后台");
      setState(() {
        _mapisshow = false;
      });
    }
  }
  @override
  initState() {
    super.initState();
    fetchUserInfo();

    XLogger.info("定位页面");
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _refreshDeviceInfo();
      getAlarm();
      showFunctionConfig();
      _loadSaveShowAnfang();
      XLogger.info("addPostFrameCallback");

      timerUtil.setOnTimerTickCallback((int value) {
        // XLogger.debug('倒计时：${value ~/ 1000}');
        setState(() {
          countDown = (value ~/ 1000);
        });
        if (countDown == 0) {
          _fetchDeviceLocation();
          getAlarm();
        }
      });
      final bottomViewHeight =
          bottomViewKey.currentContext?.size?.height ?? 120;
      setState(() {
        this.bottomViewHeight = bottomViewHeight;
      });
    });
    // _refreshDeviceInfo();

    WidgetsBinding.instance.addObserver(this);

    loadSavedString();

    PermissionManager.requestLocationPermissions(context,
        onPermissionDenied: () {
      ToastUtils.showSimpleDialog(context,
          title: '提示',
          content: '请开启定位权限',
          cancelTitle: '取消',
          confirmTitle: '去设置',
          showCancel: true, cancelCallback: () {
        context.pop();

        // Navigator.pop(context);
      }, confirmCallback: () {
        XLogger.info("requestLocationPermissions");
        Navigator.pop(context);
        PermissionManager.openSettings();
      });
    }, success: () {
      XLogger.info("同意权限");
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        _locationSuccess(result);
      });
    });
    if (Platform.isIOS) {
      //接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        _locationSuccess(result);
      });
    } else if (Platform.isAndroid) {
      //接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        _locationSuccess(result);
      });
    }
    _locationAction();
  }

  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    await _myLocPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 开始定位
  void _startLocation() async {
    if (Platform.isIOS) {
      var result = await _myLocPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      XLogger.debug('开始单次定位：${result}');
    } else if (Platform.isAndroid) {
      await _myLocPlugin.startLocation();
    }
  }

  /// 定位成功
  void _locationSuccess(BaiduLocation result) {
    //result为定位结果
    XLogger.debug(
        '定位结果：longitude:${result.longitude}, latitude:${result.latitude}, address:${result.address}');
    phoneLocation = BMFCoordinate(result.latitude!, result.longitude!);
    if (isLocation) {
      isLocation = false;
      myMapController?.setCenterCoordinate(
          BMFCoordinate(result.latitude!, result.longitude!), true);
      // _myLocPlugin.stopLocation();
    }
    if (clickLocationType == 1) {
      _drawDeviceMarker(result.latitude!, result.longitude!);
      return;
    } else if (clickLocationType == 0 && !hasLocation) {
      monitorData?.longitude = result.longitude;
      monitorData?.latitude = result.latitude;
      monitorData?.address = result.address;
      phoneAddress = result.address;
      _drawDeviceMarker(monitorData!.latitude!, monitorData!.longitude!);
      return;
    }
    XLogger.debug('result.course: ${result.course}');
    BMFLocation location = BMFLocation(
      coordinate: BMFCoordinate(result.latitude!, result.longitude!),
      altitude: result.altitude,
      horizontalAccuracy: result.radius,
      verticalAccuracy: result.verticalAccuracy,
      speed: result.speed,
      course: result.course,
    );
    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );
    myMapController?.updateLocationData(userLocation);
    // 更新样式
    BMFUserLocationDisplayParam displayParam = BMFUserLocationDisplayParam(
      accuracyCircleFillColor: Colors.blue,
      accuracyCircleStrokeColor: Colors.red,
      isAccuracyCircleShow: true,
      locationViewOffsetX: 0,
      locationViewOffsetY: 0,
      locationViewImage: 'assets/images/map/phone_location.png',
      locationViewHierarchy:
          BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM,
    );
    myMapController?.updateLocationViewWithParam(displayParam);
  }

  @override
  void dispose() {
    XLogger.info('dispose');

    timerUtil.cancel();
    _scrollController.dispose();
    _myLocPlugin.stopLocation();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用
    return Scaffold(
      // appBar: PreferredSize(
      //   preferredSize: const Size.fromHeight(kAppbarHeight),
      //   child: AppBar(
      //     title: Text(
      //       '查看定位(${deviceInfo.imei})',
      //       style: const TextStyle(
      //         fontSize: 17,
      //         color: Colors.white,
      //       ),
      //     ),
      //     centerTitle: true,
      //     backgroundColor: AppTheme.themeConfig.primaryColor,
      //     foregroundColor: Colors.white,
      //   ),
      //
      // ),
      // appBar: AppBar(
      //   leading: IconButton(
      //     onPressed: () {
      //       Navigator.pop(context);
      //     },
      //     icon: Row(
      //       mainAxisSize: MainAxisSize.min,
      //       children: [
      //         Text(' <返回'),
      //       ],
      //     ),
      //   ),
      //   title: Text(
      //     '查看定位(${deviceInfo.imei})',
      //     style: TextStyle(color: ColorUtils.hexToColor("#009FE8")),
      //   ),
      //   centerTitle: true,
      //   backgroundColor: AppTheme.themeConfig.navBarColor,
      //   foregroundColor: Colors.black26,
      //   titleTextStyle: TextStyle(),
      // ),

      body: Stack(
        children: [
          if (_mapisshow)
        BMFMapWidget(
        onBMFMapCreated: (controller) {
           onBMFMapCreated(controller);
        },
        mapOptions: mapOptions,
        ),

    _buildTopRightView(),
          _buildBottomView(),
          // _buildBottomleftView(),
          _topView()
        ],
      ),
    );
  }
}
